package com.du.yuchenweather;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.Nullable;

public abstract class BaseActivity extends Activity {
    private Intent mServiceIntent;

    private WeatherService.WeatherBinder mWeatherBinder;

    protected abstract void sendHanderToService();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mServiceIntent = new Intent(this, WeatherService.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        bindService(mServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unbindService(mServiceConnection);
    }

    private void setServiceBinder(IBinder iBinder) {
        mWeatherBinder = (WeatherService.WeatherBinder)iBinder;
        sendHanderToService();
    }

    ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            setServiceBinder(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            destoryServiceBinder();
        }
    };

    protected void destoryServiceBinder() {
        if(mWeatherBinder != null) {
            mWeatherBinder.distoryHandler();
            mWeatherBinder = null;
        }
    }
}
